import socket
import os
from Cryptodome.Cipher import DES
import base64
import binascii


def pad(text):
    """
    # 加密函数，如果text不是8的倍数【加密文本text必须为8的倍数！】，那就补足为8的倍数
    :param text:
    :return:
    """
    while len(text) % 8 != 0:
        text += ' '
    return text
# 设置密钥&建立连接
key = "qwerpoiu".encode()
des = DES.new(key, DES.MODE_ECB)
sy = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sy.connect(('127.0.0.1', 8001))
str = input("请输入您要传输的文件名：")
sy.sendall("接收密钥".encode())
print("the message from ('127.0.0.1', 8001):",sy.recv(1024).decode())
sy.sendall(base64.b64encode(key))
print("the message from ('127.0.0.1', 8001):",sy.recv(1024).decode())
sy.sendall(str.encode())
os.chdir(r"C:\Users\98606\Desktop\1924")
file = open('{}'.format(str), 'r', encoding="utf8")
text = file.read()
padded_text = pad(text)
encrypted_text = des.encrypt(padded_text.encode('utf-8'))
sy.sendall(encrypted_text)
file.close()
data = sy.recv(1024)
print("the message from ('127.0.0.1', 8001):",data.decode())
sy.sendall("receive".encode())
sy.close()